package com.nbpt;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.nbpt.db.AccountDbHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class MainActivity extends AppCompatActivity {
    TextView tvUsername;
    EditText edtUsername;
    EditText edtPasspword;
    CheckBox checkBox;
    SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edtUsername = findViewById(R.id.edtUsername);

        edtUsername.setTextColor(getResources().getColor(R.color.colorAccent));
        edtPasspword = findViewById(R.id.edtPassword);
        checkBox = findViewById(R.id.checkBox);


        sp = getSharedPreferences("MainActivity", Context.MODE_PRIVATE);
        String username = sp.getString("account", "");
        String password = sp.getString("psw", "");
        edtUsername.setText(username);
        edtPasspword.setText(password);
    }


    public void clearAll(View view) {
        Log.d("MainActivity", "点击了清除按钮");
        Toast.makeText(this, "点击了清除按钮", Toast.LENGTH_SHORT).show();

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_LONG).show();
            }else if(msg.what == 0){
                String  err = (String)msg.obj;
                Toast.makeText(MainActivity.this, err, Toast.LENGTH_LONG).show();

            }

        }
    };


    JSONObject jsonAccount = new JSONObject();

    public void login(View view) {
        String username = edtUsername.getText().toString();
        String password = edtPasspword.getText().toString();
        try {
            jsonAccount.put("password", password);
            jsonAccount.put("username", username);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                //Log.e("MainActivity", "登录系统启动" );
                HttpURLConnection connection = null;
                try {
                    URL url = new URL("http://192.168.1.7:9020/iot/user/login");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);
                    connection.setRequestProperty("connection", "Keep-Alive");
                    connection.setRequestProperty("Charset", "UTF-8");
                    connection.setRequestProperty("Content-Type", "application/json");
                    OutputStream os = connection.getOutputStream();
                    os.write(jsonAccount.toString().getBytes());
                    os.flush();
                    os.close();
                    if (connection.getResponseCode() == 200) {
                        InputStream is = connection.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                        String line;
                        String response = "";
                        while ((line = reader.readLine()) != null) {
                            response += line;
                        }
                        Log.e("MainActivity", response);
                        JSONObject jsonResponse = new JSONObject(response);
                        int code = jsonResponse.getInt("code");
                        if (code == 10001) {
                            //Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_LONG).show();
                            handler.sendEmptyMessage(1);
                            Intent intent = new Intent(MainActivity.this, MenuActivity.class);
                            startActivity(intent);
                        } else {
                            String errMrg = jsonResponse.getString("msg");
                            Message msg = new Message();
                            msg.what = 0;
                            msg.obj = errMrg;
                            handler.sendMessage(msg);

                        }
                    } else {
                        Log.e("MainActivity", "服务器返回错误");
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        /*AccountDbHelper dbHelper = new AccountDbHelper(MainActivity.this);
        Cursor cursor = dbHelper.searchAccount();
        if(cursor.getCount()>0){
            int i=0;
            boolean flag = false;
            cursor.moveToFirst();
            while (i<cursor.getCount()) {
                Log.e("MainActivity", "用户名：" + cursor.getString(1));
                if (username.equals(cursor.getString(1))) {
                    flag = true;
                    if (password.equals(cursor.getString(2))){
                        Toast.makeText(this, "登录成功", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(MainActivity.this,MenuActivity.class);
                        startActivity(intent);
                        if (checkBox.isChecked()){//勾选上的状态
                            //保存用户名和密码
                            SharedPreferences.Editor editor = sp.edit();
                            editor.putString("account",username);
                            editor.putString("psw",password);
                            editor.commit();
                            checkBox.setChecked(true);
                        }else{
                            SharedPreferences.Editor editor = sp.edit();
                            editor.clear();
                            editor.commit();
                            checkBox.setChecked(false);
                        }
                } else {
                    Toast.makeText(this, "密码有误", Toast.LENGTH_LONG).show();
                }
                break;
            }

                cursor.moveToNext();
                i++;
            }
            cursor.close();
            if(!flag){
                Toast.makeText(this, "账号未注册", Toast.LENGTH_LONG).show();
            }
        }else {
            Toast.makeText(this, "没有账号，请先注册", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(MainActivity.this, RegisterActivity1.class);
            //startActivity(intent);
            startActivityForResult(intent,0);
        }*/

    }

    public void gotoRegister(View view) {
        Intent intent = new Intent(MainActivity.this, RegisterActivity1.class);
        //startActivity(intent);
        startActivityForResult(intent, 0);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (resultCode == 1) {
                String username = data.getStringExtra("extra0");
                edtUsername.setText(username);
                String password = data.getStringExtra("extra2");
                edtPasspword.setText(password);
            }
        }
    }
}
